# coding=utf-8
from app.util.http import Response
from django.contrib import auth

def listHistory(request):
    from app.manager.models import Task
    p = request.POST
    gridDict = Task.objects.getGridDict(
        int(p['start']) if p.has_key('start') else 0,
        int(p['limit']) if p.has_key('limit') else 10,
    )
    return Response.json(gridDict)
    
    
def sqlReview(request):
    p = request.POST
    sql = p['sql']
    start = str(int(p['start']) if p.has_key('start') else 0)
    limit = str(int(p['limit']) if p.has_key('limit') else 25)
    
    if sql == '' or sql is None:
        #do something!
        1==1
    
    try:
        from MySQLdb import connect
        conn = connect(
            host = 'localhost',
            user = 'root',
            passwd = '',
            db = 'output',
            use_unicode = True,
            charset = 'utf8'
        )
        cur = conn.cursor()
        
        cur.execute('select count(*) as `count` from ('+sql+') `tmp`')
        count = cur.fetchall()[0][0]
        
        
        cur.execute('select * from ('+sql+') `tmp` limit '+start+','+limit)
        result = list(cur.fetchall())
    
        cur.close()
        conn.close()
    except BaseException,e:
        return Response.json({
            'action':Response.ActionType.alert ,
            'detail':'sql Error:<br />'+e[1]
        })
    
    
    keys = ('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z')
    
    items = []
    index = 0 
    for row in result:
        index=index+1
        item = {}
        for i in range(len(row)):
            item[keys[i]] = row[i]
        item['grid_index'] = int(start)+index
        items.append(item)
        
    
    return Response.gridJson({'count':count,'items':list(items)})
        
        
        
        
    
    
    
    